package activity

import (
	"context"
	"strconv"
	"strings"

	"mall/service/backend/api/internal/logic/promotion/util"
	"mall/service/backend/api/internal/svc"
	"mall/service/backend/api/internal/types"
	"mall/service/backend/api/internal/utils/parse"
	"mall/service/backend/common/i18n"
	"mall/service/backend/common/utils/pointy"
	"mall/service/product/rpc/productclient"
	"mall/service/promotion/rpc/promotionclient"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetActivityProductCategoryListLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetActivityProductCategoryListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetActivityProductCategoryListLogic {
	return &GetActivityProductCategoryListLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetActivityProductCategoryListLogic) GetActivityProductCategoryList(
	req *types.ActivityProductCategoryListReq,
) (resp *types.ActivityProductCategoryListResp, err error) {
	page, pageSize := parse.ParsePageInfo(
		req.Current,
		req.PageSize,
		l.svcCtx.Config.Query.DefaultAmount,
		l.svcCtx.Config.Query.MaxAmount,
	)

	var status uint32
	if req.Status != nil {
		status = *req.Status + 1
	}

	orderBys := util.ParseSorter(req.Sorter)
	filterBys := util.ParseFilter(req.Filter)

	data, err := l.svcCtx.PromotionRpc.BackendGetActivityRelationshipById(l.ctx, &promotionclient.ActivityRelationListReq{
		Page:          page,
		PageSize:      pageSize,
		ActivityId:    *req.ActivityId,
		WithCategorys: pointy.GetPointer(uint32(1)),
		Status:        &status,
		OrderBy:       orderBys,
		FilterBy:      filterBys,
	})
	if err != nil {
		return nil, err
	}

	resp = &types.ActivityProductCategoryListResp{
		BaseDataInfo: types.BaseDataInfo{
			Success: true,
			Msg:     l.svcCtx.Trans.Trans(l.ctx, i18n.Success),
		},
		Data: types.ActivityProductCategoryListInfo{
			BaseListInfo: types.BaseListInfo{
				Current:  page,
				PageSize: pageSize,
				Total:    data.GetTotal(),
			},
		},
	}

	var categoryIds []string
	for _, v := range data.Categories {
		if v.ProductCategoryId != nil && *v.ProductCategoryId > 0 {
			categoryIds = append(categoryIds, strconv.FormatInt(int64(*v.ProductCategoryId), 10))
		}
	}

	if len(categoryIds) > 0 {
		//为什么加逗号
		res, err := l.svcCtx.ProductRpc.BackendGetTermList(l.ctx, &productclient.TermListReq{
			Ids: pointy.GetPointer(strings.Join(categoryIds, ",")),
		})
		if err != nil {
			return nil, err
		}

		if len(res.List) > 0 {
			for _, v := range res.List {
				var media []*types.MediaInfo
				resp.Data.List = append(resp.Data.List, &types.ActivityProductCategoryInfo{
					CategoryId: v.Id,
					Name:       v.Name,
					Slug:       v.Slug,
					Media:      media,
				})
			}
		}
	}

	return resp, nil
}
